package com.shanghaionstar.login;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.DealersService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 6335yz on 2016/5/13.HomeOrCompanyInfoIntentService
 */
public class HomeOrCompanyInfoIntentService extends Service {
    private List<FavoriteEntity> favoriteEntitiesList;
    private UserAddressInfoImpl userAddressInfoImpl;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        favoriteEntitiesList = new ArrayList<FavoriteEntity>();
        userAddressInfoImpl = new UserAddressInfoImpl(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        getGohomeAndCompanyInfo();
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * @Title: initGohomeAndCompanyInfo
     * @Description: 初始化公司和家的地址信息
     */
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public void getGohomeAndCompanyInfo() {
        final Message msg = Message.obtain();
        DealersService service = new DealersService(Constants.CURRENT_SERVER_URL);
        RequestEntity entity = NetConnectUtil.getAuthRequestEntity(OnstarApplication.getApplication());
        entity = service.getHomeAndCompanyAddressInfo(entity, ApplicationUtil.getInstance().getIdpID());
        new Sender().send(entity, new ResponseHandler() {

            @Override
            public void onSuccess(String tag, String json) {
                if (!CommonUtil.isNull(json)) {
                    favoriteEntitiesList = new Gson().fromJson( json,new TypeToken<ArrayList<FavoriteEntity>>(){}.getType());
                    msg.what = Constants.GET_HOMECOMPANY_INFO_SUCCESS;
                } else {
                    msg.what = Constants.GET_HOMECOMPANY_INFO_ERROR;
                }
                resultHandle.sendMessage(msg);
            }

            @Override
            public void onError(String tag, HttpException e) {
                MyPost.post(new Runnable() {
                    @Override
                    public void run() {
                        msg.what = Constants.SERVICE_HTTP_ERROR;
                        resultHandle.sendMessage(msg);
                    }
                });
            }
        }, getClass(), "getGohomeAndCompanyInfo");
    }


    private Handler resultHandle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.GET_HOMECOMPANY_INFO_SUCCESS://获取家或公司的地址信息成功
                    saveHomeAndCompanyAddressInfo();
                    stopSelf();
                    break;
                case Constants.GET_HOMECOMPANY_INFO_ERROR://获取失败

                    break;
                case Constants.SERVICE_HTTP_ERROR://网络错误

                    break;
            }

        }
    };

    private PoiItemInfo gohomePoiItemInfo;
    private PoiItemInfo gocompanyPoiItemInfo;

    /**
     * @param
     * @return void
     * @Title: saveHomeAndCompanyAddressInfo
     * @Description: 保存家或公司的信息
     */
    public void saveHomeAndCompanyAddressInfo() {
        if (!CommonUtil.isNull(favoriteEntitiesList)) {
            int listSize = favoriteEntitiesList.size();
            for (int i = 0; i < listSize; i++) {
                String customCatetory = favoriteEntitiesList.get(i).getCustomCatetory();
                if ("1".equals(customCatetory)) {//家
                    gohomePoiItemInfo = getGoHomeOrCompanyPoiInfo(favoriteEntitiesList.get(i));
                    //将数据存在本地的数据库
                    userAddressInfoImpl.saveUserAddressInfo(gohomePoiItemInfo, customCatetory);
                } else if ("2".equals(customCatetory)) {//公司
                    gocompanyPoiItemInfo = getGoHomeOrCompanyPoiInfo(favoriteEntitiesList.get(i));
                    //将数据存在本地的数据库
                    userAddressInfoImpl.saveUserAddressInfo(gocompanyPoiItemInfo, customCatetory);
                }
            }
        }
    }

    public PoiItemInfo getGoHomeOrCompanyPoiInfo(FavoriteEntity favoriteEntity) {
        PoiItemInfo poiItemInfo = new PoiItemInfo();
        poiItemInfo.setTitle(favoriteEntity.getPoiName());
        poiItemInfo.setAddress(favoriteEntity.getPoiAddress());
        poiItemInfo.setLatitude(favoriteEntity.getPoiCoordinate().getLatitude());
        poiItemInfo.setLongitude(favoriteEntity.getPoiCoordinate().getLongitude());
        poiItemInfo.setCityName(favoriteEntity.getPoiCityCode());
        poiItemInfo.setTelphone(favoriteEntity.getPoiPhoneNumber());
        return poiItemInfo;
    }
}
